package p.ithorns.framework.mysql.handler;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;
import p.ithorns.framework.common.time.TimeUtil;
import p.ithorns.framework.common.utils.StringUtil;

import java.sql.*;
import java.time.LocalDateTime;

/**
 * LocalDateTimeTypeHandler
 *
 * @author Ht.L
 * @date 2023-12-14 14:56
 * @since 1.0.0
 */
@MappedTypes({LocalDateTime.class})
//@MappedJdbcTypes(JdbcType.VARCHAR)
public class SQLiteDateTimeTypeHandler implements TypeHandler<LocalDateTime> {

    private final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    @Override
    public void setParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) throws SQLException {
        if (parameter != null) {
            ps.setString(i, TimeUtil.toString(parameter, DATE_TIME_FORMAT));
        } else {
            ps.setNull(i, Types.VARCHAR);
        }
    }

    @Override
    public LocalDateTime getResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        if (StringUtil.isNotBlank(value)) {
            return TimeUtil.asLocalDateTime(value, DATE_TIME_FORMAT);
        }
        return null;
    }

    @Override
    public LocalDateTime getResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        if (StringUtil.isNotBlank(value)) {
            return TimeUtil.asLocalDateTime(value, DATE_TIME_FORMAT);
        }
        return null;
    }

    @Override
    public LocalDateTime getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        if (StringUtil.isNotBlank(value)) {
            return TimeUtil.asLocalDateTime(value);
        }
        return null;
    }

}